/*
 * 
 * LegendShop 多用户商城系统
 * 
 *  版权所有,并保留所有权利。
 * 
 */
package com.legendshop.oa.dao.impl;

import com.legendshop.dao.impl.GenericDaoImpl;
import com.legendshop.dao.support.*;
import com.legendshop.dao.sql.ConfigCode;
import com.legendshop.oa.constants.*;
import com.legendshop.oa.dao.ProjectDao;
import com.legendshop.oa.dao.ProjectModuleDao;
import com.legendshop.oa.dao.ProjectPlanDao;
import com.legendshop.oa.dto.ProjectQueryDto;
import com.legendshop.oa.dto.ProjectReport;
import com.legendshop.oa.dto.ProjectReportQueryDto;
import com.legendshop.oa.dto.Select2Dto;
import com.legendshop.oa.model.KeyValueEntity;
import com.legendshop.oa.model.Project;
import com.legendshop.oa.model.ProjectModule;
import com.legendshop.oa.model.ProjectPlan;
import com.legendshop.oa.security.UserDetail;
import com.legendshop.oa.util.PropertiesUtil;
import com.legendshop.util.AppUtils;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * The Class ProjectDaoImpl. Dao实现类
 */

public class ProjectDaoImpl extends GenericDaoImpl<Project, Long> implements ProjectDao {

	private ProjectModuleDao projectModuleDao;


	private ProjectPlanDao projectPlanDao;


	//查询用户有权限访问的项目
	private String sqlForLoadProjectsEntity = "SELECT * FROM ls_project WHERE deleted = 0 and TYPE = 1 AND status != ? UNION " + 
			"SELECT p.* FROM ls_project p, ls_project_member pm WHERE p.id = pm.project_id AND p.deleted = 0 AND p.TYPE = 0 AND p.status !=? AND ( pm.user_name = ? OR principal = ? OR tester = ?)";
	

	@Override
	public PageSupport<Project> getProject(ProjectQueryDto projectQueryDto) {


		UserDetail userDetail = projectQueryDto.getUserDetail();
		boolean isAdmin = userDetail.hasFunction(FunctionEnum.FUNCTION_VIEW_ALL_DATA);
		//boolean isAdmin = true; //都可以看， 不在限制
		SimpleSqlQuery query = new SimpleSqlQuery(Project.class, PropertiesUtil.getObject(SysParameterEnum.PAGE_SIZE, Integer.class), projectQueryDto.getCurPageNO());
		QueryMap map = new QueryMap();
		map.put("projectId", projectQueryDto.getProjectId());
		if(!isAdmin) {//管理员可以查看所有的数据
			//项目组成员，项目经理，测试主管都可以看到该项目
			map.put("userName", userDetail.getUsername());
			map.put("principal", userDetail.getUsername());
			map.put("tester", userDetail.getUsername());
		}
		map.put("type", projectQueryDto.getType());
		map.like("name", projectQueryDto.getProjectName());
		map.like("aliasName", projectQueryDto.getAliasName());
		map.like("principalRealName", projectQueryDto.getPrincipalRealName());
		map.like("testerRealName", projectQueryDto.getTesterRealName());
		if (projectQueryDto.getStatus() != null) {
			map.put("statusSQL", " and p1.status = ?");
			map.put("status", projectQueryDto.getStatus());
		} else {
			map.put("statusSQL", " and p1.status != 4"); // 默认不传值则为没有结束的项目
		}
		String querySql = null;
		String sqlCount = null;

		//判断是否为外部排序
		if (projectQueryDto.getSortResult().isSortExternal()) {
			map.put(Constants.ORDER_INDICATOR,  projectQueryDto.getSortResult().parseSeq());
 		}
		if(!isAdmin) {//管理员可以查看所有的数据
			 querySql = ConfigCode.getInstance().getCode("oa.getProjectByMember", map);
			 sqlCount = ConfigCode.getInstance().getCode("oa.getProjectCountByMember", map);
		}else {
			 querySql = ConfigCode.getInstance().getCode("oa.getProject", map);
			 sqlCount = ConfigCode.getInstance().getCode("oa.getProjectCount", map);
		}

		map.remove("statusSQL");// 前面加入了status，防止为空的情况出现
		map.remove(Constants.ORDER_INDICATOR);
		query.setParam(map.toArray());
		query.setQueryString(querySql);
		query.setAllCountString(sqlCount);

		return querySimplePage(query);

	}
	
	/**
	 * 获取项目下用户的报表
	 */
	@Override
	public List<ProjectReport> getProjectReport(ProjectReportQueryDto projectReportQueryDto) {
		QueryMap map = new QueryMap();
		map.put("projectId", projectReportQueryDto.getProjectId());
		map.put("startDate", projectReportQueryDto.getStartDate());
		map.put("endDate", projectReportQueryDto.getEndDate());
		String querySql = ConfigCode.getInstance().getCode("oa.getProjectMemberReport", map);
		return query(querySql, ProjectReport.class, map.toArray());
	}

	/**
	 * 根据商城获取列表
	 */
	public List<Project> getProject(String userName) {
		return this.queryByProperties(new EntityCriterion().eq("userName", userName));
	}

	/**
	 * 根据Id获取
	 */
	public Project getProject(Long id) {
		String sqlStr = "SELECT p.*,(SELECT u.real_name FROM ls_admin_user  u WHERE u.name = p.principal) AS principalRealName, (SELECT u.real_name FROM ls_admin_user u WHERE u.name = p.tester) AS testerRealName  FROM ls_project p where p.id = ?";
		return get(sqlStr, Project.class, id);
	}

	@Override
	public Project getProjectWithModule(Long projectId) {
		Project project = getProject(projectId);
		List<ProjectModule> modules = projectModuleDao.getProjectModuleByPro(projectId);
		project.setModules(modules);

		List<ProjectPlan> processingPlans = projectPlanDao.getProjectPlan(projectId, ProjectStatusEnum.PROCESSING.value());
		project.setPlans(processingPlans);
		return project;
	}

	/**
	 * 逻辑删除
	 */
	public int deleteProject(Project project) {
		return update("UPDATE ls_project SET deleted = 1 WHERE id = ?", project.getId());
		
	}
	
	/**
	 * 真实删除
	 */
	@Override
	public int deleteProjectTruely(Project project) {
		return delete(project);
	}

	/**
	 * 保存
	 */
	public Long saveProject(Project project) {
		return save(project);
	}

	/**
	 * 更新
	 */
	public int updateProject(Project project) {
		return update(project);
	}

	/**
	 * 查询列表
	 */
	public PageSupport getProject(CriteriaQuery cq) {
		return queryPage(cq);
	}


	@Override
	public List<KeyValueEntity> loadProjectsEntity() {
		String sql = "select * from ls_project where deleted = 0 and status != ?";
		List<Project> projects = this.query(sql, Project.class, ProjectStatusEnum.FINISH.value());// 查询尚未完成的项目
		if (AppUtils.isNotBlank(projects)) {
			List<KeyValueEntity> result = new ArrayList<KeyValueEntity>();
			for (Project project : projects) {
				KeyValueEntity entity = new KeyValueEntity(project.getId().toString(), project.getName());
				result.add(entity);
			}
			return result;
		}
		return null;
	}

	/**
	 * 查找用户能访问的项目列表
	 */
	@Override
	public List<KeyValueEntity> loadProjectsEntity(UserDetail userDetail) {
		List<Project> projects = this.query(sqlForLoadProjectsEntity, Project.class, ProjectStatusEnum.FINISH.value(),
				ProjectStatusEnum.FINISH.value(),userDetail.getUsername(),userDetail.getUsername(),userDetail.getUsername());// 查询尚未完成的项目
		if (AppUtils.isNotBlank(projects)) {
			List<KeyValueEntity> result = new ArrayList<KeyValueEntity>();
			for (Project project : projects) {
				KeyValueEntity entity = new KeyValueEntity(project.getId().toString(), project.getName());
				result.add(entity);
			}
			return result;
		}
		return null;
	}

	@Override
	public List<KeyValueEntity> loadModulesEntity(Integer projectId) {
		List<KeyValueEntity> result = this.query("select id ,name  from ls_project_module where project_id=? ", new Object[] { projectId },
				(rs, rowNum) -> new KeyValueEntity(String.valueOf(rs.getLong("id")), rs.getString("name")));
		return result;
	}

	@Override
	public List<KeyValueEntity> loadPlansEntity(Integer projectId) {
		List<KeyValueEntity> result = this.query("SELECT id ,title  FROM ls_project_plan WHERE project_id=? AND STATUS = ? AND deleted = 0 order by id desc", new Object[] { projectId, TaskStatusEnum.PROCESSING.value()},
				(rs, rowNum) -> new KeyValueEntity(String.valueOf(rs.getLong("id")), rs.getString("title")));
		return result;
	}


	@Override
	public boolean updateProjectWorkingTime(Long projectId) {
		String sql = "UPDATE ls_project p SET p.actual_hours = (SELECT SUM(t.consumed) FROM ls_taskestimate t WHERE p.id = t.project_id ) WHERE p.id = ?";
		return update(sql, projectId) > 0;
	}

	/**
	 * 查询项目列表
	 */
	@Override
	public List<Select2Dto> queryProjectList(String username, String q, Integer pageSize, Integer currPage) {
		int offset = (currPage - 1) * pageSize;
	
		QueryMap map = new QueryMap();
		map.like("projectName", q);//用于获取sql
		String querySql = ConfigCode.getInstance().getCode("oa.projectList", map);
		
		Object[] params = null; //构造参数
		if(AppUtils.isNotBlank(q)){
			String projectName = "%" + q + "%";
			params = new Object[]{ProjectStatusEnum.FINISH.value(),projectName, ProjectStatusEnum.FINISH.value(),projectName,username,username,username};
		}else{
			params = new Object[]{ProjectStatusEnum.FINISH.value(),ProjectStatusEnum.FINISH.value(),username,username,username };
		}
		
		
		return queryLimit(querySql, Select2Dto.class, offset, pageSize, params);
	}

	/**
	 * 查询用户自己本身的项目总数
	 */
	@Override
	public int projectCount(String username, String q) {
		QueryMap map = new QueryMap();
		map.like("projectName", q);//用于获取sql
		String countSql = ConfigCode.getInstance().getCode("oa.projectListCount", map);
		
		Object[] params = null; //构造参数
		if(AppUtils.isNotBlank(q)){
			String projectName = "%" + q + "%";
			params = new Object[]{ProjectStatusEnum.FINISH.value(),projectName, ProjectStatusEnum.FINISH.value(),projectName,username,username,username};
		}else{
			params = new Object[]{ProjectStatusEnum.FINISH.value(),ProjectStatusEnum.FINISH.value(),username,username,username };
		}
		
		
		return get(countSql, Integer.class, params);
	}


	public void setProjectPlanDao(ProjectPlanDao projectPlanDao) {
		this.projectPlanDao = projectPlanDao;
	}

	public void setProjectModuleDao(ProjectModuleDao projectModuleDao) {
		this.projectModuleDao = projectModuleDao;
	}

}
